﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DNNToolkit.Modules.FAQ.Components;
using DotNetNuke.Common.Lists;
using DotNetNuke.Common;
using DotNetNuke.Security;

namespace DNNToolkit.Modules.FAQ
{

    /// <summary>
    /// The ViewDNNToolkitFAQ class displays the content.
    /// </summary>
    public partial class ViewFAQ : PortalModuleBase, IActionable
    {
        #region Private Members

        private int recordCount = 0;
        private int RecordCount
        {
            get
            {
                if (recordCount == 0)
                    recordCount = int.Parse(Localization.GetString("Record.Count", this.LocalResourceFile));
                return recordCount;
            }
        }

        private string headerTemplate;
        /// <summary>
        /// Gets the template from setting.
        /// </summary>
        /// <value>The template.</value>
        private string HeaderTemplate
        {
            get
            {
                if (headerTemplate == null)
                {
                    if (!string.IsNullOrEmpty((string)Settings["headertemplate"]))
                        headerTemplate = (string)Settings["headertemplate"];
                    else
                        headerTemplate = FAQController.HeaderTemplate;
                }
                return headerTemplate;
            }
        }

        private string footerTemplate;
        /// <summary>
        /// Gets the footer template.
        /// </summary>
        /// <value>The footer template.</value>
        private string FooterTemplate
        {
            get
            {
                if (string.IsNullOrEmpty(footerTemplate))
                {
                    if (!string.IsNullOrEmpty((string)Settings["footertemplate"]))
                        footerTemplate = (string)Settings["footertemplate"];
                    else
                        footerTemplate = FAQController.FooterTemplate;                    
                }
                return footerTemplate;
            }
        }

        private List<FAQInfo> FAQList
        {
            get
            {
                if (Session["FAQList"] != null)
                    return Session["FAQList"] as List<FAQInfo>;
                else
                    return new List<FAQInfo>();
            }
            set
            {
                Session["FAQList"] = value;
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Populates the category combo.
        /// </summary>
        private void PopulateCategoryCombo()
        {
            mCategoryDropDownList.Items.Clear();
            mCategoryDropDownList.Items.Add(new ListItem(Localization.GetString("AllCategory.Text", this.LocalResourceFile),"0"));
            FAQController mgr = new FAQController();
            foreach (FAQCategoryDefinitionInfo item in mgr.GetAllFAQCategoryDefinitions())
            {
                mCategoryDropDownList.Items.Add(new ListItem(item.CategoryName,item.CategoryDefinitionID.ToString()));
            }
        }

        /// <summary>
        /// Populates the category menu.
        /// </summary>
        private void PopulateCategoryMenu()
        {
            List<FAQCategoryDefinitionInfo> list = new List<FAQCategoryDefinitionInfo>();
            FAQController mgr = new FAQController();
            foreach (FAQCategoryDefinitionInfo item in mgr.GetAllFAQCategoryDefinitions())
            {
                list.Add(item);
            }
            mCategoryList.DataSource = list;
            mCategoryList.DataBind();
        }

        /// <summary>
        /// Populates the FAQ by cat.
        /// </summary>
        /// <param name="category">The category.</param>
        private void PopulateFAQByCat(long categoryID)
        {
            SetIndex(mCategoryDropDownList, categoryID);
            FAQController controller = new FAQController();
            FAQList = controller.SearchFAQByCatetory(categoryID, this.ModuleId); ;
            mResultList_PageIndexChanging(0);
        }


        /// <summary>
        /// Sets the index.
        /// </summary>
        /// <param name="dropDownList">The drop down list.</param>
        /// <param name="value">The value.</param>
        private void SetIndex(DropDownList dropDownList, long value)
        {
            int index = 0;
            for (int i = 0; i < dropDownList.Items.Count; i++)
            {
                if (dropDownList.Items[i].Value == value.ToString())
                {
                    index = i;
                    break;
                }
            }
            dropDownList.SelectedIndex = index;
        }

        /// <summary>
        /// Populates the FAQ by filter.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="category">The category.</param>
        private void PopulateFAQByFilter(string filter, long categoryID)
        {
            mFilterTextBox.Text = filter;
            SetIndex(mCategoryDropDownList, categoryID);
            FAQController controller = new FAQController();
            List<FAQInfo> list = new List<FAQInfo>();
            if (categoryID == 0)
            {
                list.AddRange(controller.SearchFAQ(filter.Trim(), this.ModuleId));
            }
            else
            {
                list.AddRange(controller.SearchFAQByFilter(filter.Trim(), categoryID, this.ModuleId));
            }
            FAQList = list;
            mResultList_PageIndexChanging(0);
        }

        /// <summary>
        /// result list page index changing.
        /// </summary>
        /// <param name="newPageIndex">New index of the page.</param>
        protected void mResultList_PageIndexChanging(int newPageIndex)
        {
            List<FAQInfo> sourceList = FAQList;
            mPreLink.Visible = true;
            mNextLink.Visible = true;
            PageIndex = newPageIndex;
            if (newPageIndex <= 0)
            {
                PageIndex = 0;
            }
            if (newPageIndex * RecordCount > sourceList.Count)
            {
                PageIndex = sourceList.Count / RecordCount;
            }
            if (PageIndex == 0)
                mPreLink.Visible = false;
            if (PageIndex * RecordCount >= sourceList.Count - RecordCount)
                mNextLink.Visible = false;
            mResultList.DataSource = GetFAQList();
            mResultList.DataBind();
        }

        /// <summary>
        /// Gets the FAQ list.
        /// </summary>
        /// <returns></returns>
        private List<FAQInfo> GetFAQList()
        {
            List<FAQInfo> list = new List<FAQInfo>();
            List<FAQInfo> sourceList = FAQList;
            int start = PageIndex * RecordCount;
            int end = (PageIndex + 1) * RecordCount;
            for (int i = start; i < end; i++)
            {
                if (i < sourceList.Count)
                    list.Add(sourceList[i]);
            }
            return list;
        }

        /// <summary>
        /// Populates the template.
        /// </summary>
        private void PopulateTemplate()
        {
            // set header template
            Label headerTemplateLabel = new Label();
            headerTemplateLabel.Text = HeaderTemplate; 
            mHeaderSettingPlaceHolder.Controls.Clear();
            mHeaderSettingPlaceHolder.Controls.Add(headerTemplateLabel);
            
            // set footer template
            Label footerTemplateLabel = new Label();
            footerTemplateLabel.Text = FooterTemplate;
            mFooterSettingPlaceHolder.Controls.Clear();
            mFooterSettingPlaceHolder.Controls.Add(footerTemplateLabel);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Get the navcategory URL.
        /// </summary>
        /// <param name="category">The category.</param>
        /// <returns></returns>
        public string GetNavCategoryURL(string category)
        {
            List<string> paramLst = new List<string>();
            paramLst.Add("Category=" + category);
            return Globals.NavigateURL(this.TabId, "", paramLst.ToArray());
        }

        /// <summary>
        /// Display the audit.
        /// </summary>
        /// <returns></returns>
        public bool DisplayAudit()
        {
            bool retValue = false;

            if ((string)Settings["auditinfo"] == "Y")
            {
                retValue = true;
            }

            return retValue;
        }


        /// <summary>
        /// Gets or sets the index of the page.
        /// </summary>
        /// <value>The index of the page.</value>
        public int PageIndex
        {
            get
            {
                if (ViewState["PageIndex"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["PageIndex"]);
            }
            set
            {
                ViewState["PageIndex"] = value;
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Page_Load runs when the control is loaded.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                PopulateTemplate();

                if (!Page.IsPostBack)
                {
                    PopulateCategoryMenu();
                    PopulateCategoryCombo();

                    if (Request.Params["Filter"] != null && Request.Params["Category"] != null)
                        PopulateFAQByFilter(Request.Params["Filter"].ToString(), long.Parse(Request.Params["Category"].ToString()));
                    else if (Request.Params["Category"] != null)
                        PopulateFAQByCat(long.Parse(Request.Params["Category"].ToString()));
                    else
                        PopulateFAQByFilter("", 0);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc, true);
            }
        }

        protected void mlnkFAQCategory_Click(object sender, EventArgs e)
        {
            PopulateFAQByFilter("", 0);
        }

        protected void mCategoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("click"))
            {
                PopulateFAQByCat(long.Parse(e.CommandArgument.ToString()));
            }
        }

        protected void mSearchButton_Click(object sender, System.EventArgs e)
        {
            PopulateFAQByFilter(mFilterTextBox.Text, long.Parse(mCategoryDropDownList.SelectedValue));
        }

        protected void mPreLink_Click(object sender, EventArgs e)
        {
            mResultList_PageIndexChanging(PageIndex - 1);
        }

        protected void mNextLink_Click(object sender, EventArgs e)
        {
            mResultList_PageIndexChanging(PageIndex + 1);
        }

        #endregion

        #region Optional Interfaces


        /// <summary>
        /// Gets the module actions.
        /// </summary>
        /// <value>The module actions.</value>
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                Actions.Add(this.GetNextActionID(), Localization.GetString("ContentOptions.Action", this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl("EditCategory"), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        /// <summary>
        /// Gets the list URL.
        /// </summary>
        /// <returns></returns>
        private string GetListURL()
        {
            DotNetNuke.Entities.Modules.ModuleController controller = new ModuleController();
            return Globals.NavigateURL(controller.GetModuleByDefinition(this.PortalId, "Lists").TabID);
        }

        #endregion

        
    }
}